import * as fs from "node:fs";
import path from "node:path";
let packagePath = path.join(__dirname, "../../package.json");
function updatePackageJson(callback) {
  fs.readFile(packagePath, "utf8", (err, data) => {
    if (err) {
      console.error("Error reading package.json", err);
      return;
    }
    let packageJson;
    try {
      packageJson = JSON.parse(data);
    } catch (e) {
      console.error("Error parsing package.json", e);
      return;
    }
    let currentVersion = packageJson.version;
    let stage = 10;
    let inc = 1;

    function newVersion() {
      let arr = currentVersion.split(".").map((x) => +x);
      for (let i = arr.length - 1; i >= 0; i--) {
        if (arr[i] + 1 >= stage && i > 0) {
          arr[i] = 0;
        } else {
          arr[i] += inc;
          break;
        }
      }
      return arr.join(".");
    }
    packageJson.version = newVersion();
    callback && callback(packageJson.version);
    let newData = JSON.stringify(packageJson, null, 2);
    fs.writeFile(packagePath, newData, "utf8", (writeErr) => {
      if (writeErr) {
        console.error("Error writing to package.json", writeErr);
      } else {
        console.log("Package.json version updated to", packageJson.version);
      }
    });
  });
}

function updateVersion(VITE_NAME) {
  if (VITE_NAME === "开发环境") {
    return;
  }
  updatePackageJson((version) => {
    let directoryPath = __dirname + "../../../public";
    fs.readdir(directoryPath, (err, files) => {
      if (err) {
        return console.log("无法扫描目录: " + err);
      }
      files.forEach(function (file) {
        if (path.extname(file).toLowerCase() === ".txt") {
          let fullPath = path.join(directoryPath, file);
          fs.unlink(fullPath, (err) => {
            if (err) {
              console.log("删除文件时出错:", fullPath, err);
            } else {
              console.log("文件已删除:", fullPath);
              fs.writeFileSync(
                path.join(__dirname, `../../public/version.txt`),
                JSON.stringify({ version: version })
              );
            }
          });
        }
      });
    });
  });
}
export default updateVersion;
